from werobot import WeRoBot
from library.models import *
from user.models import *
import datetime
import requests
from .venify import Sign

robot =WeRoBot(
    enable_session=False,
    token='unique',
    APP_ID='wx2fab5d8fc63cdcee',
    APP_SECRET='e469f04bc8ae06b60f6a40215e46de01',
)
client = robot.client

@robot.text
def hello(message):
    return 'hello'

@robot.subscribe
def subscribe(event):
    openid = event.source
    sign_user(openid)


@robot.unsubscribe
def unsubscribe(event):
    openid = event.source
    user = User.objects.get(openid=openid)
    user.subscribe = '0'
    user.save()


def sign_user(openid):
    if not User.objects.filter(openid=openid):
        info = client.get_user_info(openid)
        info['subscribe_time'] = datetime.datetime.fromtimestamp(info['subscribe_time'])
        info['name'] = info['nickname']
        user = User.objects.create(**info)
        return user

def set_menu():
    button = {
        "button": [
            {
                "type": "scancode_push",
                "name": "借书",
                "key": "bookbill"
            },
            {
                "type": "view",
                "name": "网上图书馆",
                "url": "http://www.unihyj.cn/library/index"
            },
            {
                "type": "view",
                "name": "我的",
                "url": "http://www.unihyj.cn/user/index"
            }
        ]
    }
    result = client.create_menu(button)
    print(result)

def set_custom_menu():
    button = [
        {
            "type": "scancode_push",
            "name": "借书",
        },
        {
            "type": "view",
            "name": "网上图书馆",
            "key": "http://www.unihyj.cn/library/index"
        },
        {
            "type": "view",
            "name": "我的",
            "url": "http://www.unihyj.cn/user/index"
        }
    ]
    matchrule = {
        "group_id": '1',
    }
    result = client.create_custom_menu(button, matchrule=matchrule)
    print(result)


def jsapi(url):
    token = client.grant_token()['access_token']
    jsapi = requests.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi" % token).json()[
        'ticket']
    sign = Sign(jsapi, url)
    sign_data = {'sign': sign.sign(), 'appId': robot.config['APP_ID']}
    return sign_data


def qrcode():
    data = {
        "expire_seconds": 3600,
        "action_name": "QR_SCENE",
        "action_info": {
            "scene": {
                "scene_id": 123
            },
        }
    }
    result = client.create_qrcode(data)
    return result['ticket']